import './index.scss'
/**
 * 创建新组件之后，在all-can-use-components中添加
 * 必须应用 microCreateMinis
 * 数据必须以formData包含
 * */
import '../../directive/index'
import { microCreateMinis } from '../../minis'
import { SlickList, SlickItem, HandleDirective } from 'vue-slicksort'
import draggable from 'vuedraggable'

/** 图片广告*/
export default {
  name: 'magicCube',
  mixins: [microCreateMinis],
  directives: { handle: HandleDirective },
  data() {
    return {
      isPass:false,
      formData: {
        indicator: 1, // 选择模板
        cornerBorder: 0,  // 边角样式
        imageMargin: 0, // 图片间距
        pageMargin: 0, // 页边距
        marginTop: 0, // 上边距 
        marginBottom: 0,  // 下边距
        density:'', // 魔方密度
        imageList: []
      },
      tabList: [
        {
          icon: 'el-icon-menu',
          title: '一行两个',
        },
        {
          icon: 'el-icon-menu',
          title: '一行三个'
        },
        {
          icon: 'el-icon-menu',
          title: '一行四个'
        },
        {
          icon: 'el-icon-menu',
          title: '二左二右'
        },
        {
          icon: 'el-icon-menu',
          title: '一左二右'
        },
        {
          icon: 'el-icon-menu',
          title: '一上二下'
        },
        {
          icon: 'el-icon-menu',
          title: '一左三右'
        },
        {
          icon: 'el-icon-menu',
          title: '自定义'
        }
      ],
      active:0,
      LayoutArr:[],
      LayoutDef:[
        {name:'宽度375像素',nameOr:'或同等比例',title:''},
        {name:'宽度375像素',nameOr:'或同等比例',title:''},
        {name:'宽度375像素',nameOr:'或同等比例',title:''},
        {name:'宽度375像素',nameOr:'或同等比例',title:''}
      ],
      isChangeImg: false, // 添加图片模式
      currentEditIndex: 0, // 当前编辑的图片
      dialogChoosePages: false, // 自定义页面弹窗
      isGetChooseFeature: false, // 是否可以返回微页面
      indicatorIndex:0,

      
      
      commonCheckFieldRules: 'checkData', // 当前组件默认的规则判断函数
      mySelfCheckRules: 'mySelfCheckFun', // 我自己的验证规则函数  比如弹窗之类的
      dialogHot: false, // 是否显示热区
      dialogChooseGoods: false, // 选择商品
      isGetChooseData: false, // 开始返会商品
      cacheImage: false, // 是否是正在编辑热区的
      /** 选择图片的弹窗*/
      dialogChooseImgVisible: false, // 显示选择图片
      isGetChooseImages: false, // 返回图片
      canChooseImagesNum: 1, // 可以添加的图片数量
      currentHotEditIndex: 0, // 当前编辑的热区
      settingActive: 0,
      showTime: [],
      cacheImageActiveBox: [], // 缓存当前box list
      boxItem: { // 盒子模板
        link: '',
        type: '',
        title: '',
        left: 0,
        top: 0,
        translateX: 0,
        translateY: 0,
        width: 102,
        height: 102
      },
      linkList: [
        {
          type: 1,
          title: '商品详情页',
          link: ''
        },
        {
          type: 2,
          title: '购物车',
          link: ''
        },
        {
          type: 3,
          title: '个人中心',
          link: ''
        },
        {
          type: 4,
          title: '活动页',
          link: ''
        }
      ],
      commandInfo: {}, // 选择跳转的信息
      indicator_d_active: 1,
      densityList:[
        {value: '3',label:'3 x 3'},
        {value: '4',label:'4 x 4'},
        {value: '5',label:'5 x 5'},
        {value: '6',label:'6 x 6'},
        {value: '7',label:'7 x 7'},
      ],
      density: '5', //密度
      cubeWidth: 320, //魔方宽度
      cubeHeight: 320, //魔方高度
      selectingItem: {
          tempStart: null,
          tempEnd: null,
          start: null,
          end: null
      },
      selectedList: [], //已经生成的单元
      activeIndex:-1,
    }
  },
  watch: {
    showTime: {
      deep: true,
      handler(val) {
        this.formData.showStartTime = val[0]
        this.formData.showEndTime = val[1]
      }
    }
  },
  components: {
    draggable,
    SlickList,
    SlickItem,
    chooseGoods: () => import('@/components/choose-goods/index.vue'),
    chooseImages: () => import('@/components/new-choose-images/index.vue'),
    chooseFeature: () => import('@/components/choose-feature/index.vue')
  },
  filters: {
    typeNameFilter(val) {
      let str = ''
      switch (val) {
        case 1:
          str = '商品详情页'
          break
        case 2:
          str = '购物车'
          break
        case 3:
          str = '个人中心'
          break
        case 4:
          str = '自定义页面'
          break
      }
      return str
    }
  },
  computed: {
    //密度值
    densityNum() {
      return parseInt(this.density);
    },
    //单元魔方高度
    cubeCellHeight() {
        return this.cubeHeight / this.density;
    },
    //单元魔方宽度
    cubeCellWidth() {
        return (this.cubeWidth -this.formData.pageMargin) / this.density;
    }
  },
  created () {
    this.LayoutArr = this.LayoutDef.slice(0,2)
    this.formData.density = this.density
  },
  mounted() {
    if(this.formData.imageList.length >0){
      // this.LayoutArr = this.formData.imageList
      this.formData.imageList.forEach((item,i) => {
        this.LayoutDef[i] = item
      });
      this.LayoutArr = this.LayoutDef.slice(0,this.formData.imageList.length)
    }else{
      this.LayoutArr = this.LayoutDef.slice(0,2)
    }
    if(this.formData.indicator === 8){
      this.selectedList = this.formData.imageList
      this.density = this.formData.density
    }

  },
  methods: {
    // 自定义魔方start
    cubeClick(index){
      this.activeIndex = index
    },
    closeClick(index){
      this.$delete(this.selectedList,index)
    },
    updateSelecting() {
      //获取开始和结束之间的所有魔方单元。
      var tempStart = this.selectingItem.tempStart;
      var tempEnd = this.selectingItem.tempEnd;

      this.selectingItem.start = {
          x: Math.min(tempStart.x, tempEnd.x)
          , y: Math.min(tempStart.y, tempEnd.y)
      };
      this.selectingItem.end = {
          x: Math.max(tempStart.x, tempEnd.x)
          , y: Math.max(tempStart.y, tempEnd.y)
      };
    },
    //清除正在选择的。
    clearSelecting() {
        this.selectingItem.tempStart = null;
        this.selectingItem.tempEnd = null;
        this.selectingItem.start = null;
        this.selectingItem.end = null;
    },
    coordFromCubeEvent(event) {
        var el = event.currentTarget;
        var x = el.getAttribute('data-x');
        var y = el.getAttribute('data-y');
        return { x: x, y: y };
    },
    isContain(x, y, item) {
        return (item.start.x <= x
            && x <= item.end.x
            && item.start.y <= y
            && y <= item.end.y);
    },
    //魔方点击事件。
    onClickCubeItem(event) {
        var domclass = event.currentTarget.getAttribute('class');
        if (-1 !== domclass.indexOf('item-selected')) {
            console.log("已经被占用");
            return;
        }

        var coord = this.coordFromCubeEvent(event);

        if (null == this.selectingItem.tempStart) {
            this.selectingItem.tempStart = coord;
            this.selectingItem.tempEnd = coord;
            this.selectingItem.start = coord;
            this.selectingItem.end = coord;
            return;
        }

        this.selectingItem.tempEnd = coord;
        this.updateSelecting();

        //加入选中的。
        var selectedItem = {
            'start': this.selectingItem.start,
            'end': this.selectingItem.end
        }
        this.selectedList.push(selectedItem);
        this.activeIndex = this.selectedList.length-1
        this.clearSelecting();
    },
    onEnterCubeItem(event) {
        if (this.selectingItem.tempStart) {
            var coord = this.coordFromCubeEvent(event);
            this.selectingItem.tempEnd = coord;
            this.updateSelecting();
        }
    },
    onEnterSelected(index) {
        if (this.selectingItem.tempStart != null) {
            this.clearSelecting();
            // splice() 会先从原数组中添加/删除项目 然后返回被删除的项目。
            this.selectedList.splice(index, 1);
        }
    },
    onChangeDensity(val) {
      this.formData.density = val
      this.clearSelecting();
      this.selectedList = [];
    },
    //判断是否正在选择
    isSelecting(x, y) {
        var item = this.selectingItem;
        if (item.tempStart) {
            return this.isContain(x, y, item);
        }
        return false;
    },
    //判断是否已经选择。
    isSelected(x, y) {
        var list = this.selectedList;
        for (var i = 0; i < list.length; i++) {
            if (this.isContain(x, y, list[i])) {
                return true;
            }
        }
        return false;
    },
    //计算选中层的宽度。
    getSelectedWidth(item) {
        return (parseInt(item.end.x) - parseInt(item.start.x) + 1) * this.cubeCellWidth;
    },
    //计算选中层的高度。
    getSelectedHeight(item) {
        return (parseInt(item.end.y) - parseInt(item.start.y) + 1) * this.cubeCellHeight;
    },
    //计算选中层的右边距离。
    getSelectedTop(item) {
        return (item.start.y - 1) * this.cubeCellHeight;
    },
    //计算选中层的左边距离。
    getSelectedLeft(item) {
        return (item.start.x - 1) * this.cubeCellWidth;
    },
  // 自定义魔方end
    titleChange(i){
      if(this.formData.indicator !== 8){
        this.$set(this.formData.imageList[i],'title',this.LayoutArr[i].title)
			}
    },
    radioChange(val){
      switch(val){
        case 1:
          this.LayoutArr = this.LayoutDef.slice(0,2)
          this.formData.imageList.length = 2
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr.forEach(item => {
            item.name = "宽度375像素"
          })
          break;
        case 2:
          this.LayoutArr = this.LayoutDef.slice(0,3)
          this.formData.imageList.length = 3
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr.forEach(item => {
            item.name = "宽度250像素"
          })
          break;
        case 3:
          this.LayoutArr = this.LayoutDef.slice(0,4)
          this.formData.imageList.length = 4
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr.forEach(item => {
            item.name = "宽度188像素"
          })
          break;
        case 4:
          this.LayoutArr = this.LayoutDef.slice(0,4)
          this.formData.imageList.length = 4
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr.forEach(item => {
            item.name = "375x375像素"
          })
          break;
        case 5:
          this.LayoutArr = this.LayoutDef.slice(0,3)
          this.formData.imageList.length = 3
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr[0].name = "375x750像素"
          this.LayoutArr[1].name = "375x375像素"
          this.LayoutArr[2].name = "375x375像素"
          break;
        case 6:
          this.LayoutArr = this.LayoutDef.slice(0,3)
          this.formData.imageList.length = 3
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr[0].name = "750x375像素"
          this.LayoutArr[1].name = "375x375像素"
          this.LayoutArr[2].name = "375x375像素"
          break;
        case 7:
          this.LayoutArr = this.Layout7
          this.LayoutArr = this.LayoutDef.slice(0,4)
          this.formData.imageList.length = 4
          this.formData.imageList = this.formData.imageList.filter((item)=>{
            return item != undefined;
          })
          this.LayoutArr[0].name = "375x750像素"
          this.LayoutArr[1].name = "375x375像素"
          this.LayoutArr[2].name = "188x375像素"
          this.LayoutArr[3].name = "188x375像素"
          break;
          default:
            // this.LayoutArr =[]
      }
    },
    imgLayoutClick(index){
      this.active = index
    },
    // 添加图片
    addImgClick(index,i) {
      this.isChangeImg = true
      this.currentEditIndex = index
      this.activeIndex = index
      this.indicatorIndex = i
      this.$refs.pics.dialog = true
      this.canChooseImagesNum = 1
    },
    /** 更换图片*/
    reviseImgClick(index,i) {
      this.isChangeImg = true
      this.currentEditIndex = index
      this.activeIndex = index
      this.indicatorIndex = i
      this.$refs.pics.dialog = true
      this.canChooseImagesNum = 1
    },
    getPicsUrl(arr) {
      // console.log('arr', arr)
      // this.formData.imageList = arr
    },
    /** choose图片的回调*/
    chooseImagesEnd($item) {
      const $imgData = $item.data
      if(this.indicatorIndex === 1){
        this.formData.imageList[this.currentEditIndex] ={url: $imgData[0]} 
        this.$set(this.LayoutDef[this.currentEditIndex],'url',$imgData[0])
      }else{
        this.$set(this.selectedList[this.activeIndex],'url',$imgData[0])
        this.formData.imageList = this.selectedList
      }
      
    },
    // 请选择跳转到的页面
    choosePageClick(index,i) {
      this.currentEditIndex = index
      this.activeIndex = index
      this.indicatorIndex = i
      this.dialogChoosePages = true
    },
    chooseChooseFeaturesFun($event) {
      if(this.formData.imageList[this.currentEditIndex] === undefined){
        this.$message.error('请先添加图片！')
        return
      }
      const microType = $event.data.type === 0 && '系统页面' || $event.data.type === 1 && '功能页面' || $event.data.type === 2 && '商品详情' || $event.data.type === 3 && '商品活动'
     
      if(this.indicatorIndex !== 8){
        this.formData.imageList[this.currentEditIndex].microTitle = $event.data.title
        this.formData.imageList[this.currentEditIndex].link = $event.data.path
        this.formData.imageList[this.currentEditIndex].type = $event.data.type
        this.formData.imageList[this.currentEditIndex].microType = microType
        this.formData.imageList[this.currentEditIndex].id = $event.data.id
  
        this.$set(this.LayoutDef[this.currentEditIndex],'microTitle',$event.data.title)
        this.$set(this.LayoutDef[this.currentEditIndex],'link',$event.data.path)
        this.$set(this.LayoutDef[this.currentEditIndex],'type',$event.data.type)
        this.$set(this.LayoutDef[this.currentEditIndex],'microType',microType)
        this.$set(this.LayoutDef[this.currentEditIndex],'id',$event.data.id)
      }else{
        this.$set(this.selectedList[this.activeIndex],'microTitle',$event.data.title)
        this.$set(this.selectedList[this.activeIndex],'link',$event.data.path)
        this.$set(this.selectedList[this.activeIndex],'type',$event.data.type)
        this.$set(this.selectedList[this.activeIndex],'microType',microType)
        this.$set(this.selectedList[this.activeIndex],'id',$event.data.id)
        this.formData.imageList = this.selectedList
      }
      this.dialogChoosePages = false
    },
    sweiperChange_a(val) {
      this.indicator_d_active = val + 1
    },
    /** 切换模板*/
    changeIndicator(index) {
      this.formData.indicator = index + 1
    },
    /** 显示添加热区*/
    showHotAreaPop(index) {
      this.dialogHot = true
      this.currentEditIndex = index
      this.activeIndex = index
      this.cacheImageActiveBox = JSON.parse(JSON.stringify(this.formData.imageList[this.currentEditIndex].activeBoxs))
    },
    /** 点击添加热区*/
    addHotArea() {
      this.cacheImageActiveBox.push(JSON.parse(JSON.stringify(this.boxItem)))
    },
    /** 保存热区*/
    saveHotBox() {
      this.formData.imageList[this.currentEditIndex].activeBoxs = this.cacheImageActiveBox
      this.dialogHot = false
    },
    /** 更换图片*/
    changeImg(index) {
      this.isChangeImg = true
      this.currentEditIndex = index
      this.activeIndex = index
      this.$refs.pics.dialog = true
      this.canChooseImagesNum = 1
    },
    // 选择商品回调
    chooseGoodsFun($event) {
      if ($event.data.length) {
        this.setLinkInfo({
          title: $event.data[0].name,
          link: $event.data[0].id
        })
      }
      this.dialogChooseGoods = false
    },
    /** 设置跳转信息*/
    setLinkInfo(obj) {
      if (this.isCacheImage) { // 热区弹窗编辑模式
        this.cacheImageActiveBox[this.currentHotEditIndex].title = obj.title
        this.cacheImageActiveBox[this.currentHotEditIndex].link = obj.link
        this.cacheImageActiveBox[this.currentHotEditIndex].type = this.commandInfo.type
        this.$forceUpdate()
        return
      }
      if (this.formData.indicator === 4) { // 热区非弹窗编辑模式
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].title = obj.title
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].link = obj.link
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].type = this.commandInfo.type
      } else {
        if(obj.type !== 3){
          this.formData.imageList[this.currentEditIndex].microTitle = obj.title
          this.formData.imageList[this.currentEditIndex].link = obj.link
          this.formData.imageList[this.currentEditIndex].type = obj.type
          this.formData.imageList[this.currentEditIndex].microType = obj.microTitle
        }else{
          this.formData.imageList[this.currentEditIndex].microTitle = obj.title
          this.formData.imageList[this.currentEditIndex].link = obj.link
          this.formData.imageList[this.currentEditIndex].type = obj.type
          this.formData.imageList[this.currentEditIndex].microType = obj.microTitle
          this.formData.imageList[this.currentEditIndex].activityId = obj.activityId
          this.formData.imageList[this.currentEditIndex].goodsId = obj.goodsId
          this.formData.imageList[this.currentEditIndex].channel = obj.channel
        }

      }
      this.$forceUpdate()
    },
    /** 选择跳转路径*/
    command(eve) {
      this.isCacheImage = eve.isCacheImage || false
      this.commandInfo = eve.linkItem
      /* eslint-disable */
      if (eve.hasOwnProperty('currentHotEditIndex')) {
        this.currentHotEditIndex = eve.currentHotEditIndex
      }
      if (eve.hasOwnProperty('currentEditIndex')) {
        this.currentEditIndex = eve.currentEditIndex
        this.activeIndex =  eve.currentEditIndex
      }
      /* eslint-enable */
      if (eve.linkItem.type === 1) {
        this.dialogChooseGoods = true
        return
      }
      if (eve.linkItem.type === 4) {
        this.dialogChoosePages = true
        return
      }
      this.setLinkInfo({
        title: this.commandInfo.title,
        link: this.commandInfo.link
      })
    },
    /* 校验*/
    checkData() {
      if(this.formData.indicator === 1){
        if(this.formData.imageList.length == 2){
          this.isPass = true
        }else{
          this.isPass = false
        }
      } else if(this.formData.indicator === 2){
        if(this.formData.imageList.length == 3){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 3){
        if(this.formData.imageList.length == 4){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 4){
        if(this.formData.imageList.length == 4){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 5){
        if(this.formData.imageList.length == 3){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 6){
        if(this.formData.imageList.length == 3){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 7){
        if(this.formData.imageList.length == 4){
          this.isPass = true
        }else{
          this.isPass = false
        }
      }else if(this.formData.indicator === 8){
        if(this.formData.imageList.length > 0){
          let obj = this.formData.imageList.find(el =>{
            return  el.url === '' || el.url === undefined
          })
          if(obj === undefined){
            this.isPass = true
          }else{
            this.isPass = false
          }
        }else{
          this.isPass = false
        }
       
      }
      this.myCheckResult(this.isPass)
    },
    // 弹出哪个没有填写的
    mySelfCheckFun() {
      this.$message.error('请添加图片！')
    }
  }
}
